<template>
  <div class="chat-container">
    <header class="chat-header">
      <h1>Dialogue</h1>
    </header>
    <div class="messages-container" ref="mes">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.role]"
      >
        <div class="message-bubble">
          <span>{{ message.content }}</span>
        </div>
      </div>
    </div>
    <div class="input-container">
      <input v-model="question" placeholder="请输入..." />
      <button @click="onSubmit">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";

let question = ref("");
let mes = ref(null);
let messages = ref([
  { role: "assistant", content: "你好，有什么我可以帮你的吗？" },
]);

const onSubmit = () => {
  if (!question.value.trim()) {
    alert("请输入问题");
    return;
  }
  // 添加用户消息到消息列表
  messages.value.push({ role: "user", content: question.value });

  // 发送POST请求
  axios
    .post("http://127.0.0.1:8000/app/dialogue/", { question: question.value })
    .then((res) => {
      if (res.status === 200) {
        // 添加助手回复到消息列表
        messages.value.push({ role: "assistant", content: res.data.mes });
      }
    });

  // 清空输入框
  question.value = "";

  // 滚动到底部
  mes.value.scrollTop = mes.value.scrollHeight;
};
</script>

<style scoped>
.chat-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f0f2f5;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.chat-header {
  text-align: center;
  margin-bottom: 20px;
}

.messages-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 10px;
  background-color: #fff;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
}

.message {
  margin: 10px 0;
  display: flex;
  align-items: flex-end;
}

.message.user {
  justify-content: flex-end;
}

.message.assistant {
  justify-content: flex-start;
}

.message-bubble {
  max-width: 70%;
  padding: 10px;
  border-radius: 10px;
  word-wrap: break-word;
}

.message.user .message-bubble {
  background-color: #0084ff;
  color: #fff;
}

.message.assistant .message-bubble {
  background-color: #e0e0e0;
  color: #000;
}

.input-container {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

input {
  flex: 1;
  padding: 10px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  outline: none;
}

button {
  padding: 10px 20px;
  background-color: #0084ff;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #0078e7;
}
</style>
